package h1.sismetro.gui;


import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Calculadora extends JPanel {

	public static int largura = 300;
	public static int altura = 200;
	
	private static final long serialVersionUID = 1L;
	private JTextField display = null;
	private JPanel jPanel = null;
	private String lastCommand;
	private boolean start;
	private double result;
	private KeyListener keyListener;

	/**
	 * This is the default constructor
	 */
	public Calculadora() {
		super();
		lastCommand = "=";
		result = 0;
		start = true;
		keyListener = new java.awt.event.KeyAdapter() {
			public void keyTyped(java.awt.event.KeyEvent e) {
				if ((e.getKeyChar() >= '0' && 
					e.getKeyChar() <='9') ||
					e.getKeyChar() == '.') {
					inserirNumero(e.getKeyChar() + "");
				} else {
					switch (e.getKeyChar()) {
						case '-':
						case '+':
						case '/':
						case '*':
						case '=':
							inserirComando(e.getKeyChar() + "");
							break;
						case KeyEvent.VK_ENTER:
							inserirComando("=");
					}
				}
			}
		};

		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setLayout(new BorderLayout());
		this.add(getDisplay(), BorderLayout.NORTH);
		this.add(getJPanel(), BorderLayout.CENTER);
	}

	/**
	 * This method initializes display	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getDisplay() {
		if (display == null) {
			display = new JTextField();
			display.setEnabled(false);
			display.setText("" + result);
			display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
			display.addKeyListener(keyListener);
		}
		return display;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			GridLayout gridLayout = new GridLayout();
			gridLayout.setRows(5);
			gridLayout.setHgap(4);
			gridLayout.setVgap(4);
			gridLayout.setColumns(4);
			jPanel = new JPanel();
			jPanel.setLayout(gridLayout);

			CommandAction command = new CommandAction();
			InsertAction insert   = new InsertAction();
			ExtraAction extra   = new ExtraAction();

			addButton("Bsp", extra, "Apagar o último caractere");
			addButton("CE", extra, "Apagar a última entrada");
			addButton("CLR", extra, "Apagar tudo");
			addButton("+-", extra, "Troca sinal");

			
			addButton("7", insert, null);
			addButton("8", insert, null);
			addButton("9", insert, null);
			addButton("/", command, null);

			addButton("4", insert, null);
			addButton("5", insert, null);
			addButton("6", insert, null);
			addButton("*", command, null);

			addButton("1", insert, null);
			addButton("2", insert, null);
			addButton("3", insert, null);
			addButton("-", command, null);

			addButton("0", insert, null);
			addButton(".", insert, null);
			addButton("=", command, null);
			addButton("+", command, null);



		}
		return jPanel;
	}
	private void addButton(String label, ActionListener listener, String hint) {
		JButton button = new JButton(label);
		button.addActionListener(listener);
		button.addKeyListener(keyListener);
		button.setToolTipText(hint);
		jPanel.add(button);

	}
	private class CommandAction implements ActionListener {

		//@Override
		public void actionPerformed(ActionEvent e) {
			String command = e.getActionCommand();
			inserirComando(command);
		}

	}
	private class InsertAction implements ActionListener {

		//@Override
		public void actionPerformed(ActionEvent e) {
			String input = e.getActionCommand();
			inserirNumero(input);
		}

	}
	
	private class ExtraAction implements ActionListener {

		//@Override
		public void actionPerformed(ActionEvent e) {
			String extra = e.getActionCommand();
			String displayText = display.getText();
			
			if (extra.equalsIgnoreCase("Bsp")) {
				if (displayText.length() > 1) {
					display.setText(display.getText().substring(0, displayText.length()-1));
				}
			} else if (extra.equalsIgnoreCase("CE")) {
				display.setText("" + result);
				start = true;
			} else if (extra.equalsIgnoreCase("CLR")) {
				result = 0;
				display.setText("" + result);
				lastCommand = "=";
				start = true;
			} else if (extra.equals("+-")) {
				if (display.getText().indexOf("-") < 0) { // número positivo
					display.setText("-" + display.getText());
				} else {
					display.setText(display.getText().replaceFirst("-", ""));
				}
			}
		}

	}

	public void calculate(double x) {
		if (lastCommand.equals("+")) result += x;
		else if (lastCommand.equals("-")) result -= x;
		else if (lastCommand.equals("*")) result *= x;
		else if (lastCommand.equals("/")) {
			result /= x;
			if (result == Double.POSITIVE_INFINITY ||
					result == Double.NEGATIVE_INFINITY) {
				result = 0;
			}
		}
		else if (lastCommand.equals("=")) result = x;

		getDisplay().setText("" + result);
	}

	public void inserirComando(String command) {
		if (start) {
			if (command.equals("-")) {
				getDisplay().setText(command);
				start = false;
			} else {
				lastCommand = command;
			}
		} else {
			calculate(Double.parseDouble(getDisplay().getText()));
			lastCommand = command;
			start = true;
		}
	}

	public void inserirNumero(String input) {
		if (start) {
			getDisplay().setText("");
			start = false;
		}
		if (!input.equals(".") || getDisplay().getText().indexOf('.') < 0) {
			getDisplay().setText(getDisplay().getText() + input);				
		}
		
	}
}
